package cn.lastjune.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.lastjune.pojo.Employee;
import cn.lastjune.service.EmployeeService;
import cn.lastjune.util.NumberUtil;
import cn.lastjune.util.Page;

@Controller
@RequestMapping("/employee")
public class EmployeeController
{

    /**
     * @param args
     */
    @Autowired
    EmployeeService employeeService;

    public String emptyJson = "{metaData:{totalProperty : 'total',root : "
            + "'result',fields: ['EmployeeID','Name','Contact'" + ",'Password']},total:0, result : []}";

    @RequestMapping(method = RequestMethod.GET)
    public void getAllEmployee(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        final Page<Employee> page = new Page<Employee>();
        int start=request.getParameter("start")==null?0:NumberUtil.parseInt(request.getParameter("start"));
        int limit=request.getParameter("limit")==null?11:NumberUtil.parseInt(request.getParameter("limit"));
        page.setPageNo(start/limit+1);
        page.setPageSize(limit); 
        final Page<Employee> result = employeeService.getAllEmployee(page);
        final List<Employee> list = result.getResult();
        StringBuilder sb = new StringBuilder();
        int count = list.size();
        if (count > 0)
        {
            String jsonHead = "{" + "metaData:{" + "totalProperty : 'total'," + "root : 'result',"
                    + "fields: ['EmployeeID','Name','Contact','Password']}," + "total:" + result.getTotalCount() + ", result : [";
            sb.append(jsonHead);

            for (Employee e : list)
            {
                count--;
                sb.append("{" + "EmployeeID : '" + e.getEmployeeid() + "'," + "Name : '" + e.getEmployeename() + "',"
                        + "Contact: '" + e.getContact() + "'," + "Password: '" + e.getPassword() + "'" + "}");
                if (count > 0)
                {
                    sb.append(",");
                }
            }
            sb.append("]}");
            System.out.println(sb);
        }
        else
        {
            sb.append(emptyJson);
        }
        String sbnew = sb.toString().replace("null", "");
        out.print(sbnew);
        out.flush();
    }

    @RequestMapping(method = RequestMethod.POST)
    public void modifyEmployee(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        response.setHeader("Charset", "UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/json"); // 解决后台数据中文乱码
        response.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        String employeeid = request.getParameter("EmployeeID");
        String employeename = request.getParameter("EmployeeName");
        String contact = request.getParameter("Contact");
        Employee e = new Employee();
        e.setEmployeeid(employeeid);
        e.setEmployeename(employeename);
        e.setContact(contact);
        if ("add".equals(method))
        {
            try
            {
                employeeService.insertEmployee(e);
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }

        }
        if ("edit".equals(method))
        {
            try
            {
                employeeService.updateEmployee(e);
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
        if ("delete".equals(method))
        {
            try
            {
                String ids[] = request.getParameterValues("ids");
                for (String id : ids)
                {
                    employeeService.deleteEmployee(id);
                }
                out.print("{success:true,msg:\'yes\'}");
                out.flush();
                return;
            }
            catch (Exception e2)
            {
                out.print("{success:false,msg:\'no\'},{failure:true}");
                out.flush();
                return;
            }
        }
        if("suggest".equals(method)){
        	String name=request.getParameter("Name");
        	List<Employee> l=employeeService.getByName(name);
        	StringBuilder sb2 = new StringBuilder();
            int count = l.size();
            if (count > 0)
            {
                String jsonHead = "{" + "metaData:{" + "totalProperty : 'total'," + "root : 'result',"
                        + "fields: ['Name']}," + "total:" + count + ", result : [";
                sb2.append(jsonHead);

                for (Employee e2 : l)
                {
                    count--;
                    sb2.append("{" +"Name : '" + e2.getEmployeename() +  "'" + "}");
                    if (count > 0)
                    {
                        sb2.append(",");
                    }
                }
                sb2.append("]}");
                System.out.println(sb2);
            }
            else
            {
                sb2.append(emptyJson);
            }
            String sbnew = sb2.toString().replace("null", "");
            out.print(sbnew);
            out.flush();
        }
    }
}
